package com.tyqx.detectcputemperaturesendmessage.util;

import com.tyqx.detectcputemperaturesendmessage.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class AnalysisUtil {

    private static final Logger logger = LoggerFactory.getLogger(AnalysisUtil.class);

    @Resource
    private Constant constant;

    public  Integer ChiaDebugLogAnalysisUtil(){

        String chiaLogPath = constant.chia_log_path;
        Integer chiaPlotNum = 0;
        File file = new File(chiaLogPath);
        if(!file.exists()){
            return 0;
        }
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            List<String> chiaLogHarvesterList = new ArrayList<>();
            reader = new BufferedReader(new FileReader(file));
            String chiaLogTempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((chiaLogTempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + chiaLogTempString);
                boolean flag = chiaLogTempString.contains("harvester chia.harvester.harvester: INFO");
                if(flag){
                    chiaLogHarvesterList.add(chiaLogTempString);
                }
                line++;
            }
            String chiaLogHarvesterBackStr = chiaLogHarvesterList.get(chiaLogHarvesterList.size()-1);
            chiaLogHarvesterBackStr = chiaLogHarvesterBackStr.substring(chiaLogHarvesterBackStr.lastIndexOf("Total ") + "Total ".length(),chiaLogHarvesterBackStr.lastIndexOf(" plots"));
            if(!chiaLogHarvesterBackStr.equals("")&& null !=chiaLogHarvesterBackStr)
                chiaPlotNum = Integer.valueOf(chiaLogHarvesterBackStr);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }


        return chiaPlotNum;
    }
}
